import services from '@/services/role';
import {ActionType, PageContainer, ProColumns, ProFormSelect, ProTable,} from '@ant-design/pro-components';
import {Button, Divider, message, Modal} from 'antd';
import React, {useRef, useState} from 'react';
import CreateForm from './components/CreateForm';

const {rolePage, addRole, deleteByCodes, enabled, disable} = services.RoleController;


/**
 * 添加角色
 * @param fields
 */
const roleAdd = async (fields: API.RoleAdd) => {
    const hide = message.loading('正在添加');
    try {
        await addRole({...fields});
        hide();
        message.success('添加成功');
        return true;
    } catch (error) {
        hide();
        message.error('添加失败请重试！');
        return false;
    }
};

/**
 *  删除角色
 * @param codes
 */
const handleRemove = async (code: string) => {
    const hide = message.loading('正在删除');
    if (!code) return true;
    try {
        await deleteByCodes([code]);
        hide();
        message.success('删除成功');
        return true;
    } catch (error) {
        hide();
        // message.error('删除失败，请重试');
        return false;
    }
};

const TableList: React.FC<unknown> = () => {
    const [createModalVisible, handleModalVisible] = useState<boolean>(false);
    const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
    const [stepFormValues, setStepFormValues] = useState({});
    const actionRef = useRef<ActionType>();
    const [current, setCurrent] = useState(1); // 当前页码
    const [pageSize, setPageSize] = useState(10); // 每页显示条数


    /**
     * 停用/启用角色
     * @param record
     */
    const handleToggleStatus = async (record: API.RoleVO) => {
        const hide = message.loading('正在处理');
        try {
            // 启用变禁用
            if(record.status===1){
                await disable([record.code]);
            }else{
                await enabled([record.code]);
            }
            hide();
            message.success(`${record.status === 1 ? '禁用' : '启用'}成功`);
            if (actionRef.current) {
                actionRef.current.reload();
            }
            return true;
        } catch (error) {
        hide();
        message.error('操作失败，请重试');
        return false;
        }
    };

    const columns: ProColumns<API.RoleVO>[] = [
        {
            title: '排序',
            dataIndex: 'sort',
            valueType: 'text',
            hideInForm: true,
            search: false,
        },
        {
            title: '代码',
            dataIndex: 'code',
            tooltip: '唯一的 key',
            search: false,
            formItemProps: {
                rules: [
                    {
                        required: true,
                        message: '名称为必填项',
                    },
                ],
            },
        },
        {
            title: '角色',
            dataIndex: 'name',
            valueType: 'text',
            formItemProps: {
                rules: [
                    {
                        required: true,
                        message: '角色为必填项',
                    },
                ],
            },
        },

        {
            title: '状态',
            dataIndex: 'status',
            valueEnum: {
                0: {text: '禁用', status: '0'},
                1: {text: '启用', status: '1'},
            },
            valueType: 'select',
            search: {
                transform: (value) => (value === '1' ? 1 : 0),
            },
            // Default value for the form
            renderFormItem: (item, { type, defaultRender, ...rest }, form) => {
                if (type === 'form') {
                // Apply default value only for the form, not search
                return (
                    <ProFormSelect
                        {...rest}
                        valueEnum={{
                            0: '禁用',
                            1: '启用',
                        }}
                        fieldProps={{
                            defaultValue: '1',
                            placeholder: '请选择状态',
                        }}
                    />
                );
                }
                return defaultRender(item);
            },
        },
        {
            title: '类型',
            dataIndex: 'type',
            hideInForm: true,
            search: false,
            initialValue: ['2'],
            valueEnum: {
                1: {text: '内置', type: '1'},
                2: {text: '自建', type: '2'},
            },
        },
        {
            title: '操作',
            dataIndex: 'option',
            valueType: 'option',
            render: (_, record) => (
                <>
                    <a
                        onClick={() => {
                        Modal.confirm({
                            title: '确认删除',
                            content: `确定要删除角色 ${record.name} 吗？`,
                            okText: '确认',
                            okType: 'danger',
                            cancelText: '取消',
                            onOk: async () => {
                            const success = await handleRemove(record.code);;
                            if (success) {
                                actionRef.current?.reloadAndRest?.();
                            }
                            },
                        });
                        }}
                    >
                        {record.type ===2 ? '删除' : ''}
                    </a>
                    <Divider type="vertical" />
                    <a
                        onClick={() => {
                            Modal.confirm({
                                title: `确认${record.status === 1 ? '禁用' : '启用'}`,
                                content: `确定要${record.status === 1 ? '禁用' : '启用'} 角色 ${record.name} 吗？`,
                                okText: '确认',
                                okType: 'primary',
                                cancelText: '取消',
                                onOk: async () => {
                                await handleToggleStatus(record);
                                },
                            });
                            }}
                    >

                        {record.type ===2 ? (record.status === 1 ? '禁用' : '启用') : ''}
                    </a>
                </>
            ),
        },
    ];

    return (
        <PageContainer
            header={{
                title: '',
            }}
        >
            <ProTable<API.RoleVO>
                headerTitle="查询用户"
                actionRef={actionRef}
                rowKey="id"
                search={{
                    labelWidth: 120,
                }}
                toolBarRender={() => [
                    <Button
                        key="1"
                        type="primary"
                        onClick={() => handleModalVisible(true)}
                    >
                        新增
                    </Button>,
                ]}
                pagination={{
                    current, // 当前页码
                    pageSize, // 每页条数
                    showSizeChanger: true, // 是否可以改变 pageSize
                    pageSizeOptions: ['5', '10', '20', '50'], // 自定义每页条数下拉选项
                    onChange: (page, pageSize) => { // 页码或 pageSize 改变的回调。
                      setCurrent(page);
                      setPageSize(pageSize);
                    },
                    onShowSizeChange: (current, size) => {// pageSize 改变的回调。
                      setCurrent(current);
                      setPageSize(size);
                    },
                  }}
                // , sorter, filter
                request={async (params) => {
                    const find: API.RolePage = {
                        name: params.name ? params.name : undefined,
                        status: params.status ? params.status : undefined,
                        page: {
                            pageIndex: params.current,
                            pageSize: params.pageSize,
                        },
                    };
                    const {data, success} = await rolePage({
                        ...find,
                        // FIXME: remove @ts-ignore
                        // @ts-ignore
                        // sorter,
                        // filter,
                    });
                    return {
                        data: data?.rows || [],
                        total: data?.total,
                        pageSize: data?.pageSize,
                        current: data?.currentPage,
                        success,
                    };
                }}
                columns={columns}
            />
            <CreateForm
                onCancel={() => handleModalVisible(false)}
                modalVisible={createModalVisible}
            >
                <ProTable<API.RoleVO, API.RoleVO>
                    onSubmit={async (value) => {
                        const success = await roleAdd(value);
                        if (success) {
                            handleModalVisible(false);
                            if (actionRef.current) {
                                actionRef.current.reload();
                            }
                        }
                    }}
                    rowKey="id"
                    type="form"
                    columns={columns}
                />
            </CreateForm>

        </PageContainer>
    );
};

export default TableList;
